package net;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket=null;

    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        socket=new Socket(serverIp,serverPort);
    }

    public void start(){
        System.out.println("启动客户端！\n");
        Scanner scanner=new Scanner(System.in);
        try(InputStream inputStream=socket.getInputStream()){
            try(OutputStream outputStream=socket.getOutputStream()){
                Scanner respScanner=new Scanner(inputStream);
                while (true){
                    System.out.println("-> ");
                    String request=scanner.next();
                    PrintWriter writer=new PrintWriter(outputStream);
                    writer.println(request);
                    writer.flush();
                    String response=respScanner.next();
                    System.out.printf("req: %s, resp:%s\n",request,response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client=new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }

}
